import { Filter, ObjectId } from "mongodb"
import db from "../db"
import { FetchAPI, LogMessage, BaseInfo } from "../interfaces"

/** 查询日志 */
export const log_all: FetchAPI<Filter<LogMessage & BaseInfo>, Array<LogMessage & BaseInfo>> = async (
  query = {},
  { loginUser },
) => {
  const conn = await db.getCollection('log')
  const messages = await conn.find({
    ...query,
    to: loginUser.username,
  }).toArray()
  return {
    success: true,
    data: messages,
  }
}

/** 获取某条日志之后所有更新过的日志 */
export const log_after_id: FetchAPI<{ _id: string }, Array<LogMessage & BaseInfo>> = async (
  { _id },
  { loginUser }
) => {
  const conn = await db.getCollection('log')
  const log = await conn.findOne({ _id: new ObjectId(_id) })
  if (!log) {
    return {
      success: true,
      data: []
    }
  }
  const messages = await conn.find({
    gmt_modified: {
      $gte: log.gmt_created,
    },
    to: loginUser.username,
  }).toArray()
  return {
    success: true,
    data: messages,
  }
}
